<template>
  <div class="clearfix">
    <a-upload
      :action="uploadUrl"
      :headers="{ token: token }"
      list-type="picture-card"
      :file-list="fileList"
      :disabled="disabled"
      :before-upload="beforeUpload"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="!disabled && fileList.length < limit">
        <a-icon type="plus" />
        <div class="ant-upload-text"></div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
import { mapGetters } from 'vuex'
export default {
  name: 'imgUpload',
  computed: {
    ...mapGetters(['token']),
  },
  props: {
    uploadUrl: {
      type: String,
      default: process.env.VUE_APP_API_BASE_URL + '/sys-center/api/common/upload',
    },
    no: {
      type: String,
      default: '1',
    },
    limit: {
      type: Number,
      default: 1000,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      fileList: [],
      ids: [],
    }
  },
  methods: {
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    beforeUpload(file) {
      console.log('beforeUpload', file)
      const isJPG = file.type === 'image/jpg'
      const isJPEG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 50
      if (!isJPG && !isJPEG && !isPNG) {
        this.$message.error('上传图片必须是JPG/JPEG/PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 50MB!')
        return false
      }
      const is = file.name.indexOf('#') == -1
      if (!is) {
        this.$message.error('文件名不能包含特殊字符#!')
        return false
      }
      return (isJPG || isJPEG || isPNG) && isLt2M && is
    },
    handleChange({ fileList }) {
      // console.log('fileList', fileList)
      this.fileList = []
      this.ids = []
      fileList.forEach((item, index) => {
        if (item.response) {
          // 最后一次走才会有response响应结果
          if (item.response.code != 200) {
            // 上传错误时
            this.$message.error(item.response.msg)
            fileList.splice(index, 1)
            return
          }
        }
        if (!item.status) {
          // 上传格式错误时
          fileList.splice(index, 1)
          return
        }
        if (item.status == 'done' && item.response) {
          // 上传格式正确时
          this.ids.push(item.response.data.accessoryId)
          item.accessoryId = item.response.data.accessoryId
          item.dataType = this.no
        } else {
          // 回显格式正确时
          this.ids.push(item.id)
          item.accessoryId = item.id
          item.dataType = this.no
        }
      })
      this.fileList = [...fileList]
      this.$emit('getFiles', this.fileList, this.ids, this.no)
    },
    inits(fileList) {
      if (!fileList || fileList.length == 0) {
        return
      }
      var arr = []
      this.ids = []
      fileList.forEach((item) => {
        arr.push({
          url: item.previewPath,
          name: item.accessoryName,
          id: item.accessoryId,
          status: 'done',
          uid: item.accessoryId,
        })
        this.ids.push(item.accessoryId)
      })
      this.fileList = arr
      this.$emit('getFiles', this.fileList, this.ids, this.no)
    },
    clears() {
      this.fileList = []
      this.ids = []
    },
  },
}
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>